package com.mhxy.handler;

import cn.hutool.core.util.StrUtil;
import com.mhxy.entity.TableData;
import com.mhxy.entity.TaskThreadInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 任务进度
 */
@Slf4j
public class TaskProgressHandler {

    private static final Map<String, TaskThreadInfo> taskThreadInfoMap = new ConcurrentHashMap<>();

    /**
     * 验证句柄线程是否正在运行
     */
    public static boolean checkHwndUserThreadIsRun(String hwndName) {
        TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
        if (info == null) {
            return false;
        }
        return info.getIsRun();
    }

    public static void setRun(String hwndName, Boolean isRun) {
        TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
        if (info == null) {
            return;
        }
        info.setIsRun(isRun);
    }

    /**
     * 添加任务
     */
    public static void addTasks(String hwndName, List<String> taskList) {
        try {
            TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
            if (info == null) {
                info = new TaskThreadInfo(hwndName);
                taskThreadInfoMap.put(hwndName, info);
            }
            info.addTask(taskList);
            log.debug("添加任务到队列: {} -> {}", hwndName, taskList);
        } catch (Exception e) {
            log.error("添加任务失败", e);
        }
    }

    /**
     * 从队列中取出一个任务
     */
    public static String poolTask(String hwndName) {
        try {
            TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
            if (info == null) {
                log.warn("未找到任务线程信息: {}", hwndName);
                return null;
            }
            String task = info.poolTask();
            log.debug("从队列取出任务: {} -> {}", hwndName, task);
            return task;
        } catch (Exception e) {
            log.error("取出任务失败", e);
            return null;
        }
    }

    /**
     * 清空队列中的任务
     */
    public static void clearTasks(String hwndName) {
        TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
        if (info != null) {
            info.clearTask();
            info.setIsRun(false);   // 停止任务
        }
        Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (Thread thread : threads) {
            if (thread.getName().equals(hwndName)) {
                System.out.println("Terminating thread: " + thread.getName());
                thread.interrupt(); // 中断线程
            }
        }
    }

    /**
     * 获取队列中等待执行的任务
     */
    public static String getAllTaskName(String hwndName) {
        TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
        if (info != null) {
            return info.peekTask();
        }
        return "";
    }

    /**
     * 获取任务进度
     */
    public static String getTaskProgress(String hwndName) {
        TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
        if (info != null) {
            return info.getTaskProgress();
        }
        return "";
    }

    public static void setTableData(TableData tableData) {
        TaskThreadInfo info = taskThreadInfoMap.get(tableData.getHwndName());
        if (info == null) {
            return;
        }
        tableData.setWaitTasks(info.poolTask());
        tableData.setTaskProgress(info.getTaskProgress());
    }

    public static void updateEndProgress() {
        String hwndName = Thread.currentThread().getName();
        taskThreadInfoMap.get(hwndName).setIsRun(false);
    }

    public static void updateStartProgress() {
        String hwndName = Thread.currentThread().getName();
        taskThreadInfoMap.get(hwndName).setIsRun(true);
    }

    /**
     * 更新任务进度
     */
    public static void updateProgress(String taskInfo, String progress) {
        try {
            String hwndName = Thread.currentThread().getName();
            TaskThreadInfo info = taskThreadInfoMap.get(hwndName);
            if (info == null) {
                log.warn("未找到任务线程信息: {}", hwndName);
                return;
            }
            
            String taskProgress = StrUtil.format("{} ({})", taskInfo, progress);
            info.setTaskProgress(taskProgress);
            log.debug("任务进度更新: {} -> {}", taskInfo, progress);
            
        } catch (Exception e) {
            log.error("更新任务进度失败", e);
        }
    }
}
